package com.gpipe.tools;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;

import com.gpipe.dbwriter.Mysql;
import com.gpipe.dirwatcher.DirectorySnapshot;
import com.gpipe.dirwatcherRealtime.DirectorySnapshotRealtime;
import com.gpipe.dirwatcherRealtime.InitialMethod;
import com.gpipe.properties.InputProperties;

public class GpipeInit {

    public static final String VariableStart = "${";

    public static final String VariableEnd = "}";

    public static int bufferSize = 4096;

    private static double EARTH_RADIUS = 6371.393;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 计算两个经纬度之间的距离(单位：米)
     *
     * @param lat1 第一个点的经度
     * @param lng1 第一个点的纬度
     * @param lat2 第二个点的经度
     * @param lng2 第二个点的纬度
     * @return 返回距离（单位：米）
     */
    public static double getDistance(double lng1, double lat1, double lng2, double lat2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 1000);
        return s;
    }

    public static double getDistance(String lng1, String lat1, String lng2, String lat2) {
        return getDistance(Double.parseDouble(lng1), Double.parseDouble(lat1), Double.parseDouble(lng2), Double.parseDouble(lat2));
    }

    public static String get15minBefore(String time) {
        return getPeriodBefore(time, "15");
    }

    public static String getPeriodBefore(String time, String periodMin) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar cal = Calendar.getInstance();
        int hour = 0, minute = 0;
        try {
            Date date = format.parse(time);
            cal.setTime(date);
            hour = cal.get(Calendar.HOUR_OF_DAY);
            minute = cal.get(Calendar.MINUTE);
            int totalMin = hour * 60 + minute;
            hour = (int) Math.floor(Math.floor(totalMin / Integer.parseInt(periodMin)) * Integer.parseInt(periodMin) / 60);
            minute = (int) Math.floor(totalMin / Integer.parseInt(periodMin)) * Integer.parseInt(periodMin) % 60;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return String.format("%02d", hour) + String.format("%02d", minute);
    }


    public static String changeMonth(String month, int offset) {
        Calendar c = Calendar.getInstance();//获得一个日历的实例
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        try {
            c.setTime(sdf.parse(month));//设置日历时间
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.add(Calendar.MONTH, offset);//在日历的月份上增加6个月
        return sdf.format(c.getTime());
    }

    public static String changeToDir(String dirPath) {
        if (dirPath.charAt(dirPath.length() - 1) != '/') {
            dirPath = dirPath + "/";
        }
        return dirPath;
    }

    public static String getExtension(String f) {
        String ext = "";
        int i = f.lastIndexOf('.');
        if (i > 0 && i < f.length() - 1) {
            ext = f.substring(i + 1);
        }
        return ext;
    }

    public static String fillValue(String _fillValue, String _value) {
        int __startIndex = _value.indexOf(VariableStart);
        if (__startIndex < 0) {
            return _value;
        }

        String __tmpValue = _value.substring(0, __startIndex);
        int __endIndex = _value.indexOf(VariableEnd, __startIndex + VariableStart.length());
        if (__endIndex < 0) {
            return __tmpValue;
        }
        __tmpValue += _fillValue;
        String __afterValue = _value.substring(__endIndex + VariableEnd.length());
        __tmpValue += __afterValue;
        return __tmpValue;
    }

    public static boolean isEmpty(String value) {
        if (value == null || "".equals(value.trim())) {
            return true;
        }
        return false;
    }

    public static boolean isNotEmpty(String value) {
        if (value == null || "".equals(value.trim())) {
            return false;
        }
        return true;
    }

    public static void unZip(GZIPInputStream in, FileOutputStream out) {
        try {
            byte[] buf = new byte[bufferSize];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            if (in != null) {
                in = null;
            }
            if (out != null) {
                out = null;
            }
        } catch (IOException e) {
            System.err.println("Fail to doUncompressFile caused by :" + e.getMessage());
        }
    }

    //Fill Data
    public static BufferedReader unZipOutReader(String _fileName) throws FileNotFoundException {

        BufferedReader reader = null;

        if (_fileName.contains(".gz")) {
            try {
                reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(_fileName)), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(_fileName)));
        }
        return reader;
    }


    public static void writeLogBufferToFile(String log, String logFilePath) {
        try {
            BufferedWriter writeLogs = new BufferedWriter(new FileWriter(logFilePath, true));
            writeLogs.write(log + "\n");
            if (writeLogs != null) {
                writeLogs.flush();
                writeLogs.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean checkTagFileName(String fileName, String tagContent) {
        boolean isValid = false;
        if (isEmpty(tagContent)) {
            isValid = true;
            return isValid;
        }
        String[] tags = tagContent.split(",");
        for (String tag : tags) {
            if (fileName.lastIndexOf(tag) != -1) {
                isValid = true;
                break;
            }
        }
        return isValid;
    }

    public static String writeLogs(String msg) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(System.currentTimeMillis());
        System.out.println(time + ":" + msg);
        return time;
    }

    public static long duration(String beginT, String endT) {
        return duration(beginT, endT, null);

    }

    public static long duration(String beginT, String endT, String pattern) {
        if (isEmpty(pattern)) {
            pattern = "yyyyMMddHHmmss";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

        Date dateB = null;
        Date dateE = null;
        try {
            dateB = simpleDateFormat.parse(beginT);
            dateE = simpleDateFormat.parse(endT);
        } catch (ParseException e) {
            writeLogs("date format is wrong,beginT="+beginT+",endT="+endT);
//            e.printStackTrace();
            return 0;
        }
        long timeB = dateB.getTime();
        long timeE = dateE.getTime();
        long interval = Math.abs((timeB - timeE)) / 1000;
        return interval;
    }

    public static String returnBiggerStr(String str1, String str2) {
        String str3 = str1.substring(str1.indexOf("interface_") + "interface_".length(), str1.indexOf(".cdr"));
        String str4 = str2.substring(str2.indexOf("interface_") + "interface_".length(), str2.indexOf(".cdr"));
        String result = null;
        if (!str1bigThenstr2(str3, str4)) {
            result = str2;
        } else {
            result = str1;
        }

        return result;
    }

    public static String returnSmallerStr(String str1, String str2) {
        str1 = str1.substring(str1.indexOf("interface_") + "interface_".length(), str1.indexOf(".cdr"));
        str2 = str2.substring(str2.indexOf("interface_") + "interface_".length(), str2.indexOf(".cdr"));
        String result = null;
        if (!str1bigThenstr2(str1, str2)) {
            result = str1;
        } else {
            result = str2;
        }

        return result;
    }

    public static boolean str1bigstr2(String str1, String str2) {
        if (Integer.parseInt(str1) - Integer.parseInt(str2) > 0) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean str1bigThenstr2(String str1, String str2) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        long int1 = 0;
        long int2 = 0;
        try {
            int1 = simpleDateFormat.parse(str1).getTime() / 1000;
            int2 = simpleDateFormat.parse(str2).getTime() / 1000;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (int1 - int2 >= 0) {
            return true;
        } else {
            return false;
        }


    }

    public static int returnSmallInt(int int1, int int2) {
        int result = 0;
        if (int1 - int2 <= 0) {
            result = int1;
        } else {
            result = int2;
        }

        return result;
    }

    public static String returnnearFileName(String lastFileName, String fileName, String nearFileName, int StaticInterval) {

        int interval = getInterval(lastFileName, fileName);
        interval = Math.abs(interval - StaticInterval);

        if (nearFileName == null) {
            return fileName;
        } else {
            int minVal = getInterval(lastFileName, nearFileName);
            minVal = Math.abs(minVal - StaticInterval);

            if (minVal - interval < 0) {
                return nearFileName;
            } else {
                return fileName;
            }
        }
    }

    public static String getIncreTimePeriod(String beginTime, String timePeriod, String outFormat) {
        String inFormat = "yyyyMMddHHmmss";
        return getIncreTimePeriodOptional(beginTime, timePeriod, outFormat, inFormat);
    }

    public static String getIncreTimePeriodOptional(String beginTime, String timePeriod, String outFormat, String inFormat) {
//		beginTime=0000   0时0分
        Calendar c = Calendar.getInstance();//获得一个日历的实例
        SimpleDateFormat sdf = new SimpleDateFormat(inFormat);
        SimpleDateFormat sdf1 = new SimpleDateFormat(outFormat);
        try {
            c.setTime(sdf.parse(beginTime));//设置日历时间
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.add(Calendar.MINUTE, Integer.parseInt(timePeriod));
        return sdf1.format(c.getTime());
    }

    public static String getIncreDayPeriodOptional(String beginDay, String dayPeriod, String outFormat, String inFormat) {
//		beginTime=0000   0时0分
        Calendar c = Calendar.getInstance();//获得一个日历的实例
        SimpleDateFormat sdf = new SimpleDateFormat(inFormat);
        SimpleDateFormat sdf1 = new SimpleDateFormat(outFormat);
        try {
            c.setTime(sdf.parse(beginDay));//设置日历时间
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.add(Calendar.DATE, Integer.parseInt(dayPeriod));
        return sdf1.format(c.getTime());
    }


    //Fill Data
    public static String plusTheInterval(String lastFileName, int interval, String suffix) {
        lastFileName = lastFileName.substring(lastFileName.indexOf("interface_") + "interface_".length(), lastFileName.indexOf(suffix));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        long tmpint = 0;
        try {
            tmpint = simpleDateFormat.parse(lastFileName).getTime() / 1000 + interval;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String result = "interface_" + simpleDateFormat.format(new Date(tmpint * 1000)) + suffix;
        return result;
    }

    public static boolean inOneHour(String lastFileName, String fileName) throws ParseException {
        return inOneHourFD(lastFileName, fileName, ".cdr");
    }

    //Fill Data
    public static boolean inOneHourFD(String lastFileName, String fileName, String suffix) throws ParseException {
        String result = null;
        lastFileName = lastFileName.substring(lastFileName.indexOf("interface_") + "interface_".length(), lastFileName.indexOf(suffix));
        fileName = fileName.substring(fileName.indexOf("interface_") + "interface_".length(), fileName.indexOf(suffix));

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Long lastLong = simpleDateFormat.parse(lastFileName).getTime() / 1000;
        Long fileLong = simpleDateFormat.parse(fileName).getTime() / 1000;
        if (lastLong - fileLong < DirectorySnapshotRealtime.statInterval && lastLong - fileLong > 0) {
            return true;
        } else {
            return false;
        }
    }

    //Fill Data
    public static boolean betweenTwoFN(String firstFileName, String lastFileName, String fileName, String suffix) throws ParseException {
        String result = null;
        lastFileName = lastFileName.substring(lastFileName.indexOf("interface_") + "interface_".length(), lastFileName.indexOf(suffix));
        firstFileName = firstFileName.substring(firstFileName.indexOf("interface_") + "interface_".length(), firstFileName.indexOf(suffix));
        fileName = fileName.substring(fileName.indexOf("interface_") + "interface_".length(), fileName.indexOf(suffix));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Long lastLong = simpleDateFormat.parse(lastFileName).getTime() / 1000;
        Long firstLong = simpleDateFormat.parse(firstFileName).getTime() / 1000;
        Long fileLong = simpleDateFormat.parse(fileName).getTime() / 1000;

        if (fileLong - firstLong > 0 && fileLong - lastLong <= 0) {
            return true;
        } else {
            return false;
        }
    }

    public static int getInterval(String bigTime, String smallTime) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = null, date1 = null;
        try {
            date = simpleDateFormat.parse(bigTime);
            date1 = simpleDateFormat.parse(smallTime);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long bigtime = date.getTime();
        long smalltime = date1.getTime();
        int interval = (int) (bigtime - smalltime) / 1000;
        return interval;
    }

    public static String proportionRound(String num) {
        return String.valueOf((int) Math.floor(Integer.parseInt(num) / DirectorySnapshotRealtime.proportion));
    }

    public static String getPath() {
        // jar path :/home/zhengrx/lib/test.jar result of
        // getPath():/home/zhengrx/lib
        URL url = GpipeInit.class.getProtectionDomain().getCodeSource().getLocation();
        String filePath = null;
        try {
            filePath = URLDecoder.decode(url.getPath(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (filePath.endsWith(".jar")) {
            filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
        }

        File file = new File(filePath);
        filePath = file.getAbsolutePath();
        return filePath;
    }

    public static boolean isLastDayOfMonth(String dateString) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = null;
        try {
            date = sdf.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DATE, (calendar.get(Calendar.DATE) + 1));
        if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {
            return true;
        }
        return false;
    }


    public static void main(String[] args) throws ParseException {

        String[] t= new String[]{"df","d"};
        System.out.println(t);
//        String result = getIncreDayPeriodOptional("20170701", "-7", "yyyyMMdd", "yyyyMMdd");
//        System.out.println("result=" + result);
    }

}
